// axios基础封装
import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/user'
import router from '@/router'

const axiosInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// 请求拦截器
axiosInstance.interceptors.request.use(config => {
  const userStore = useUserStore()
  // 按照后端要求拼接token数据
  const { token } = userStore.userInfo
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// 响应拦截器
axiosInstance.interceptors.response.use(({ data }) => {
  return data
}, e => {
  // 统一错误提示
  ElMessage({
    type: 'error',
    message: e.response.data.message
  })

  // 401 Token失效处理
  const userStore = useUserStore()
  if (e.response.status === 401) {
    userStore.clearUserInfo()
    router.push('/login')
  }
  return Promise.reject(e)
})

export default axiosInstance
